package com.EventHandler;

import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;

import com.Dao.NewsDao;
import com.example.myapplication.ArticleActivity;
import com.example.myapplication.R;
import com.news.model.News;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 负责加载文章数据并更新UI。
 */
public class ArticleLoader {
    private Context context;
    private NewsDao newsDao;
    private int newsId;

    private TextView article_title;
    private TextView author;
    private TextView publish_time;
    private TextView article_content;

    public ArticleLoader(Context context, int newsId) {
        this.context = context;
        this.newsId = newsId;
        newsDao = new NewsDao(context);
    }

    public void initializeUI() {
        article_title = ((ArticleActivity) context).findViewById(R.id.article_title);
        author = ((ArticleActivity) context).findViewById(R.id.author);
        publish_time = ((ArticleActivity) context).findViewById(R.id.publish_time);
        article_content = ((ArticleActivity) context).findViewById(R.id.article_content);
    }

    private String formatDate(long time) {
        Date date = new Date(time); // 假设时间戳是秒级单位，需要转换为毫秒级
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return sdf.format(date);
    }

    public void loadData() {
        //Log.i("加载数据","新闻id" + newsId);
        News news = newsDao.getNewsByNewsid(newsId);
        if (news != null) {
            article_title.setText(news.getTitle());
            author.setText(news.getAuthor());
            publish_time.setText(formatDate(news.getPublishedAt()));
            article_content.setText(news.getContent());

        } else {
            Toast.makeText(context, "无法加载新闻", Toast.LENGTH_SHORT).show();
        }

    }

    public void close() {
        newsDao.close();
    }
}
